using Microsoft.EntityFrameworkCore;
using SG3L_RAG.Domain.Entities;
using SG3L_RAG.Domain.Repositories;
using SG3L_RAG.Infrastructure.Persistence;

namespace SG3L_RAG.Infrastructure.Repositories;

public class Repository<T> : IRepository<T> where T : class
{
    private readonly SG3LDbContext _context;

    public Repository(SG3LDbContext context)
    {
        _context = context;
    }

    public async Task<T?> GetByIdAsync(Guid id)
    {
        return await _context.Set<T>().FindAsync(id);
    }

    public async Task<IEnumerable<T>> GetAllAsync()
    {
        return await _context.Set<T>().ToListAsync();
    }

    public async Task AddAsync(T entity)
    {
        await _context.Set<T>().AddAsync(entity);
        await _context.SaveChangesAsync();
    }

    public async Task UpdateAsync(T entity)
    {
        _context.Set<T>().Update(entity);
        await _context.SaveChangesAsync();
    }

    public async Task DeleteAsync(Guid id)
    {
        var entity = await GetByIdAsync(id);
        if (entity != null)
        {
            _context.Set<T>().Remove(entity);
            await _context.SaveChangesAsync();
        }
    }

    public async Task AddRangeAsync(IEnumerable<T> entities)
    {
        await _context.Set<T>().AddRangeAsync(entities);
        await _context.SaveChangesAsync();
    }

    public async Task DeleteRangeAsync(IEnumerable<Guid> ids)
    {
        if (!typeof(EntityBase).IsAssignableFrom(typeof(T)))
            throw new InvalidOperationException($"{typeof(T).Name} 必须继承 EntityBase 才能批量删除。");

        var entities = await _context.Set<T>()
            .Cast<EntityBase>()
            .Where(e => ids.Contains(e.Id))
            .Cast<T>()
            .ToListAsync();
        if (entities.Any())
        {
            _context.Set<T>().RemoveRange(entities);
            await _context.SaveChangesAsync();
        }
    }
}